<template>
  <div class="content-detail">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header
          icon="el-icon-arrow-left"
          content="创建新项目"
          @back="goback"
        >
        </el-page-header>
        <div class="card-box--downloadbtn">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>项目基础信息</span>

          <div v-if="showInfo" @click="showInfo = !showInfo" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="showInfo = !showInfo" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <el-form
          :model="formData"
          class="content-box"
          :rules="rules"
          ref="formDataRef"
          label-width="160px"
          v-show="showInfo"
          @click="handleDeptList(false)"
        >
          <el-form-item label="项目名称" prop="projectName">
            <el-input
              v-model.trim="formData.projectName"
              class="width-custom200"
            ></el-input>
            <span class="tip">
              注意：项目类型为A类项目时，此页面默认创建最高级项目，其子项目及其合同信息可在单项目空间中创建维护。
            </span>
          </el-form-item>
          <el-form-item label="项目类型" prop="projectTypeCode">
            <el-select
              v-model="formData.projectTypeCode"
              value-key="dicCode"
              @change="handleChangeType"
              class="width-custom200"
            >
              <el-option
                class="default-option"
                v-for="item in projectTypeList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目所属工厂" prop="projectFactoryCode">
            <el-input
              v-model.trim="filterText"
              class="width-custom200"
              @click.stop="handleDeptList(true)"
            ></el-input>
            <el-tree
              clearable
              ref="treeRef"
              class="filter-tree"
              :data="deptList"
              :props="defaultProps"
              default-expand-all
              :filter-node-method="filterNode"
              v-if="showDeptList"
              @node-click="handleChangeDept"
            />
          </el-form-item>
          <el-form-item label="项目管理员" prop="projectLeaderId">
            <el-select
              v-model="formData.projectLeaderId"
              filterable
              remote
              placeholder="请输入姓名"
              :remote-method="getTableData"
              class="width-custom200"
            >
              <el-option
                v-for="item in userList"
                :key="item.value"
                :label="item.label"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目年度" prop="projectYear">
            <el-date-picker
              v-model="formData.projectYear"
              type="year"
              value-format="YYYY"
              placeholder="项目年度"
              class="width-custom200"
            ></el-date-picker>
            <span class="tip">
              注意：项目类型为A类项目时，选择项目立项的年份。
            </span>
          </el-form-item>
          <el-form-item
            label="项目模板"
            prop="projectTmpId"
            v-if="formData.projectTypeCode.dicCode === 'B'"
          >
            <el-select
              v-model="formData.projectTmpId"
              value-key="id"
              class="width-custom200"
              @change="handleChangeTemp"
            >
              <el-option
                class="default-option"
                v-for="item in templateList"
                :label="item.projectTemplateName"
                :key="item.id"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目描述" prop="remarks">
            <el-input
              type="textarea"
              v-model.trim="formData.remarks"
              :rows="3"
            ></el-input>
          </el-form-item>
        </el-form>
      </el-collapse-transition>
    </el-card>
    <el-card class="card-box" v-if="formData.projectTmpId">
      <template #header>
        <div class="card-box-header">
          <span>项目模版配置</span>

          <div v-if="showSet" @click="showSet = !showSet" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="showSet = !showSet" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <div v-show="showSet" class="content-box">
          <status-task-edit
            ref="editRef"
            :mode="isEdit ? 'edit' : 'read'"
            :templateId="templateId"
            :data="proStageList"
            :checkbox="true"
          ></status-task-edit>
        </div>
      </el-collapse-transition>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRefs, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import { getUserList } from "/@/api/user";
import {
  addProject,
  projectTemplateList,
  getDeptTree,
  getTemplateInfo
} from "/@/api/projects";
import { postDictList } from "/@/api/home";
import { ElMessageBox } from "element-plus";
import StatusTaskEdit from "../../../components/template/index.vue";

export default defineComponent({
  components: { StatusTaskEdit },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const formDataRef = ref<HTMLFormElement | null>(null) as any;
    const editRef = ref<HTMLFormElement | null>(null) as any;
    const treeRef = ref<HTMLFormElement | null>(null) as any;
    let userList = ref([]);
    let projectTypeList = ref([]);
    let templateList = ref([]);
    let deptList = ref([]);

    let state = reactive({
      formData: {
        // projectCode: "",
        projectLeaderId: "" as any,
        projectLeaderName: "",
        projectName: "",
        projectTmpId: null,
        projectTypeCode: "" as any,
        projectTypeName: "",
        projectRegionCode: "",
        projectRegionName: "",
        projectFactoryCode: "",
        projectFactoryName: "",
        projectYear: "",
        remarks: ""
      },
      showInfo: true,
      showSet: true,
      defaultProps: {
        children: "children",
        label: "deptDescShrt"
      },
      showDeptList: false
    });

    let stageCheckedkeys = ref([]);
    let taskCheckedkeys = ref([]);
    let isEdit = true;
    let templateId = ref();
    let projectTemplateInfo = {};
    const filterNode = (value: string, data) => {
      if (!value) return true;
      return data.deptDescShrt.includes(value);
    };

    let proStageList = ref([]);

    const rules = {
      projectName: [
        { required: true, message: "请填写项目名称", trigger: "blur" },
        { min: 3, max: 60, message: "长度在 3 到 60 个字符", trigger: "blur" }
      ],
      projectTypeCode: [
        { required: true, message: "请选择项目类型", trigger: "change" }
      ],
      projectFactoryCode: [
        { required: true, message: "请选择项目所属工厂", trigger: "change" }
      ],
      projectLeaderId: [
        { required: true, message: "请填写项目负责人", trigger: "change" }
      ],
      projectYear: [
        { required: true, message: "请选择项目年度", trigger: "change" }
      ],
      projectTmpId: [
        { required: true, message: "请选择项目模板", trigger: "change" }
      ]
    };

    const filterText = ref("");
    watch(filterText, val => {
      treeRef.value!.filter(val);
    });

    // 项目类型
    const initProjectTypeList = async () => {
      try {
        const { data } = await postDictList({ dicType: "thd_pro_type" });
        projectTypeList.value = data || [];
      } catch (err) {
        console.log(err);
      }
    };
    initProjectTypeList();

    // 工厂区域
    const getDeptTreeFunc = async () => {
      try {
        const { data } = await getDeptTree({});
        deptList.value = data || [];
      } catch (err) {
        console.log(err);
      }
    };
    getDeptTreeFunc();

    // 模板类型
    const initTemplateTypeList = async code => {
      try {
        const { data } = await projectTemplateList({
          isOriginal: "1",
          projectTemplateNameLike: "",
          projectTmpTypeCode: code || "",
          createUserNameLike: "",
          createTimeStrStart: "",
          createTimeStrEnd: "",
          pageNum: 1,
          pageSize: 0
        });
        templateList.value = data.list || [];
      } catch (err) {
        console.log(err);
      }
    };

    const handleChangeType = () => {
      let tmpTypeCode = state.formData.projectTypeCode;
      let code = tmpTypeCode ? tmpTypeCode.dicCode : "";
      if (code === "B") {
        initTemplateTypeList(code);
      } else {
        state.formData.projectTmpId = null;
      }
    };

    const goback = () => {
      router.push("/projects/manage/space");
    };

    const getTableData = async (query = "") => {
      if (!query) {
        userList.value = [];
        return;
      }
      try {
        const params = {
          pageNum: 1,
          pageSize: 100,
          nameLike: query
        };
        const { code, data } = await getUserList(params);
        if (code === 200) {
          userList.value = data.list.map(item => {
            return { value: item.id, label: `${item.name}(${item.userName})` };
          });
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleSave = async () => {
      try {
        const isValid = await new Promise(resolve =>
          formDataRef.value.validate(resolve)
        );
        if (!isValid) return;
        if (state.formData.projectTmpId) {
          editRef.value
            .save()
            .then(async data => {
              // 简化data中的参数
              let arr = [];
              data.forEach((item, index) => {
                let obj = {
                  index,
                  projectStageName: item.projectStageName
                } as any;
                let taskList = [];
                item.proTmpTaskList.forEach(task => {
                  let taskObj = {
                    approvalForm: task.approvalForm,
                    approvalNodeCode: task.approvalNodeCode,
                    approvalNodeName: task.approvalNodeCode,
                    approvalNodeTmpAttachmentArr:
                      task.approvalNodeTmpAttachmentArr,
                    taskName: task.taskName
                  };
                  taskList.push(taskObj);
                });
                obj.proTmpTaskList = [...taskList];
                arr.push(obj);
              });
              submitAddProject(arr);
            })
            .catch(err => {
              console.log("error", err);
              NotifMessage.warning(err);
            });
        } else {
          let arr = [];
          submitAddProject(arr);
        }
      } catch (err) {
        console.log(err, "00000");
      }
    };

    const submitAddProject = arr => {
      const params = {
        ...state.formData,
        projectTmpId: state.formData.projectTmpId?.id,
        projectTypeName: state.formData.projectTypeCode?.dicValue,
        projectTypeCode: state.formData.projectTypeCode?.dicCode,
        projectLeaderName: state.formData.projectLeaderId?.label,
        projectLeaderId: state.formData.projectLeaderId?.value + "",
        projectRegionCode: state.formData.projectRegionCode,
        projectRegionName: state.formData.projectRegionName,
        projectFactoryCode: state.formData.projectFactoryCode,
        projectFactoryName: state.formData.projectFactoryName,
        newProjectTemplate: {
          ...projectTemplateInfo,
          proStageList: arr
        }
      };
      ElMessageBox.confirm("保存后将无法修改，确认保存吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info"
      }).then(async () => {
        const { code, message } = await addProject(params);
        commonBackFn(code, message);
        console.log("params", params);
      });
    };

    const commonBackFn = (code: Number, message: String) => {
      if (code === 200) {
        NotifMessage.success(message);
        goback();
      } else {
        if (!message) return;
        NotifMessage.error(message);
      }
    };

    const handleDeptList = flag => {
      state.showDeptList = flag;
    };

    const handleChangeDept = (node, nodeObj) => {
      let parent = nodeObj.isLeaf && nodeObj.level == 3 && nodeObj.parent.data;
      let data = nodeObj.data;
      state.formData.projectRegionCode = parent.id;
      state.formData.projectRegionName = parent.deptDescShrt;
      state.formData.projectFactoryCode = data.id;
      state.formData.projectFactoryName = data.deptDescShrt;
      if (nodeObj.isLeaf && nodeObj.level == 3) {
        state.showDeptList = false;
        filterText.value = data.deptDescShrt;
      }
    };

    const getData = async templateId => {
      try {
        const { code, data } = await getTemplateInfo({ id: templateId });
        if (code === 200) {
          const {
            projectTemplateName,
            projectTmpTypeCode,
            projectTmpTypeName,
            remarks,
            proStageList: proStageListData
          } = data;
          projectTemplateInfo = {
            projectTemplateName,
            projectTmpTypeCode,
            projectTmpTypeName,
            remarks
          };
          proStageList.value = [...proStageListData];
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleChangeTemp = () => {
      // 请求模板数据
      let id = state.formData.projectTmpId?.id;
      templateId.value = id;
      getData(id);
    };

    return {
      ...toRefs(state),
      formDataRef,
      editRef,
      userList,
      projectTypeList,
      templateList,
      rules,
      route,
      goback,
      getTableData,
      handleSave,
      handleChangeType,
      proStageList,

      deptList,
      treeRef,
      handleDeptList,
      handleChangeDept,
      filterText,

      isEdit,
      templateId,

      filterNode,
      handleChangeTemp,
      stageCheckedkeys,
      taskCheckedkeys
    };
  }
});
</script>
<style lang="scss" scoped>
.filter-tree:deep {
  &.el-tree {
    position: absolute;
    top: 36px;
    width: 400px;
    max-height: 226px;
    overflow: auto;
    border: 1px solid #e4e8f2;
    z-index: 10;
  }
}
</style>
